#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initialize();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initialize()
{
    m_settingsDialog = new SettingsDialog(this);
    m_textSearchDialog = new TextSearchDialog(this);

    popMenu_L = new QMenu();
    QAction *actionDelDir = new QAction("删除");
    popMenu_L->addAction(actionDelDir);
    connect(actionDelDir, &QAction::triggered, this, &MainWindow::deleteDir);

    QAction *actionShowDir = new QAction("在Explorer中显示");
    popMenu_L->addAction(actionShowDir);
    connect(actionShowDir, &QAction::triggered, this, &MainWindow::showDir);

    popMenu_R = new QMenu();
    QAction *actionDelFile = new QAction("删除");
    popMenu_R->addAction(actionDelFile);
    connect(actionDelFile, &QAction::triggered, this, &MainWindow::deleteFile);

    QAction *actionShowFile = new QAction("在Explorer中显示");
    popMenu_R->addAction(actionShowFile);
    connect(actionShowFile, &QAction::triggered, this, &MainWindow::showFile);

    // 添加搜索按钮
//    QAction* searchAction = new QAction(QIcon(":/icons/search.png"), tr("Search"), this);
//    searchAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H));
//    ui->toolBar->addAction(searchAction);
    connect(ui->actionSearch, &QAction::triggered, m_textSearchDialog, &QDialog::show);
    connect(ui->actionMoveSelectedLinesUp, &QAction::triggered, this, &MainWindow::moveSelectedLinesUp);
    connect(ui->actionMoveSelectedLinesDown, &QAction::triggered, this, &MainWindow::moveSelectedLinesDown);
    //==================================
    connect(ui->actionNew, &QAction::triggered, this, &MainWindow::newDocument);
    connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::open);
    connect(ui->actionSave, &QAction::triggered, this, &MainWindow::save);
    connect(ui->actionSave_as, &QAction::triggered, this, &MainWindow::saveAsAct);
    connect(ui->actionCopy, &QAction::triggered, this, &MainWindow::copy);
    connect(ui->actionCut, &QAction::triggered, this, &MainWindow::cut);
    connect(ui->actionPaste, &QAction::triggered, this, &MainWindow::paste);
    connect(ui->actionUndo, &QAction::triggered, this, &MainWindow::undo);
    connect(ui->actionRedo, &QAction::triggered, this, &MainWindow::redo);
    connect(ui->actionFont, &QAction::triggered, this, &MainWindow::selectFont);
    //connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
    connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAboutDialog);
    connect(ui->actionExit, &QAction::triggered, this, &MainWindow::exit);
    //m_settingsDialog
    connect(ui->actionSetting, &QAction::triggered, m_settingsDialog, &QDialog::show);
    //
    //QsciScintilla 必须使用 SIGNAL SLOT 方式连接信号槽
    //connect(ui->frame, &QsciScintilla::textChanged, this, &MainWindow::on_textArea_textChanged);
    connect(ui->frame, SIGNAL(textChanged()), this, SLOT(on_textArea_textChanged()));

    connect(ui->frame, SIGNAL(SCN_FOCUSIN()), this, SLOT(scn_focusin()));//获得焦点
    connect(ui->frame, SIGNAL(SCN_FOCUSOUT()), this, SLOT(scn_focusout()));//失去焦点

    // 监听主题变更
    connect(m_settingsDialog, &SettingsDialog::themeChanged, this, &MainWindow::setDarkTheme);

    //==============================
    //为了去除菜单栏和工具栏之间的一条白线
    //QToolTip { background-color: white; color: black; font-size: 18px; }
    //QToolBar { border: 0px; background: transparent; }
    ui->toolBar->setStyleSheet("QToolBar { border: 0px; background: transparent; }");
    //ui->menubar->setStyleSheet("QMenuBar { border: 0px; background: transparent; }");

    list1 = ui->list1;
    list2 = ui->list2;
    m_textArea = ui->textArea;
    m_frame = ui->frame;
    list1->setFrameShape(QListWidget::NoFrame);
    list2->setFrameShape(QListWidget::NoFrame);
    QToolBar *toolBar = ui->toolBar;
    toolBar->setIconSize(QSize(34,34));//默认24

    settingManage = SettingManage::getInstance();
    settings = settingManage->getSettings();
    m_textArea->setFrameShape(QFrame::Shape::NoFrame);
    textAreaType = settings->value("Notes/textAreaType", 1).toInt();
    switch (textAreaType) {
    case 0:
        m_textArea->setVisible(true);
        m_frame->setVisible(false);
        break;
    case 1:
        m_textArea->setVisible(false);
        m_frame->setVisible(true);
        break;
    default:
        m_textArea->setVisible(false);
        m_frame->setVisible(true);
    }
    //
    QFont listFont = settingManage->getListFont();
    list1->setFont(listFont);
    list2->setFont(listFont);
    QFont font = settingManage->getTextFont();
    this->updateTextFont(font);


    rootPath = settingManage->getRootPath();

    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenRect = screen->availableVirtualGeometry();
    int window_wide = settings->value("Notes/window_wide", screenRect.width() * 0.6).toInt();
    int window_high = settings->value("Notes/window_high", screenRect.height() * 0.6).toInt();
    int window_x = settings->value("Notes/window_x", -1).toInt();
    int window_y = settings->value("Notes/window_y", -1).toInt();
    resize(window_wide, window_high);
    if (window_x != -1 || window_y != -1) {
        move(window_x, window_y);
    }

    int savedState = settings->value("Notes/WindowState", static_cast<int>(Qt::WindowNoState)).toInt();
    this->setWindowState(static_cast<Qt::WindowStates>(savedState));

    isDarkTheme = settings->value("Notes/isDarkTheme", false).toBool();
    setthemeColor();
    cleanTextArea();
    LayoutUtils::setLayoutSize(ui->splitter, ui->splitter_2);
    //
    m_textArea->setFrameShape(QFrame::Shape::NoFrame);
    setSelectColor();
    //----------------------------
    QString aList1Value = settings->value("Notes/list1Value", "").toString();
    QString aList2Value = settings->value("Notes/list2Value", "").toString();

    QStringList aList1 = FileUtils::getDirList(rootPath);
    WidgetUtils::putListItem(list1, aList1);

    QString aList1Path = QDir(rootPath).filePath(aList1Value);
    QStringList aList2 = FileUtils::getFileList(aList1Path);
    WidgetUtils::putListItem(list2, aList2);

    int list1_row = MyUtils::getStringListIndexByValue(aList1,aList1Value);
    int list2_row = MyUtils::getStringListIndexByValue(aList2,aList2Value);

    if (list1_row != -1) list1->setCurrentRow(list1_row);
    if (list2_row != -1) list2->setCurrentRow(list2_row);

    int verticalScroll = settings->value("TextEdit/verticalScroll", 0).toInt();
    if (textAreaType == 0) {//textArea
        //设置光标位置
        int position = settings->value("TextEdit/position", 0).toInt();
        QTextCursor textCursor = m_textArea->textCursor();
        textCursor.setPosition(position);
        m_textArea->setTextCursor(textCursor);
        //设置滚动条位置
        if (verticalScroll != 0) m_textArea->verticalScrollBar()->setSliderPosition(verticalScroll);
    }
    else if (textAreaType == 1) {//ui->frame
        //设置光标位置
        int line = settings->value("TextEdit/CursorPosition_line", 0).toInt();
        int index = settings->value("TextEdit/CursorPosition_index", 0).toInt();
        m_frame->setCursorPosition(line, index);
        //m_frame->setCaretLineBackgroundColor(Qt::lightGray);
        m_frame->SendScintilla(QsciScintilla::SCI_SETFIRSTVISIBLELINE, line);
        //设置滚动条位置
        if (verticalScroll != 0) m_frame->verticalScrollBar()->setSliderPosition(verticalScroll);
    }
}

void MainWindow::setthemeColor()
{
    setDarkTheme(isDarkTheme);
    if (isDarkTheme) {
        defaultTextColorName = "white";

        if (textAreaType == 1) {//ui->frame
            // 设置当前行的背景颜色
            m_frame->setCaretLineBackgroundColor(QColor("#26282e"));

            // 设置全局背景颜色为黑色，字体颜色为白色
            m_frame->setPaper(QColor("#000000"));  // 黑色背景
            m_frame->setColor(QColor("#FFFFFF")); // 白色字体

            // 设置选中区域的背景颜色和字体颜色
            m_frame->SendScintilla(QsciScintilla::SCI_SETSELBACK, 1, QColor("#D3D3D3").rgba()); // 灰白色选中背景
            m_frame->SendScintilla(QsciScintilla::SCI_SETSELFORE, 1, QColor("#000000").rgba()); // 黑色选中文字

            //行号颜色
            m_frame->setMarginsBackgroundColor(QColor("#1e1f22")); // 设置行号背景颜色
            m_frame->setMarginsForegroundColor(QColor("#4b5059")); // 设置行号文字颜色
        }
    }
    else {
        defaultTextColorName = "#000000";
        // 设置菜单栏背景颜色
        ui->menubar->setStyleSheet("QMenuBar {"
                                   "background-color: #f0f0f0; "
                                   "}");

        if (textAreaType == 1) {//ui->frame
            // 设置当前行的背景颜色
            m_frame->setCaretLineBackgroundColor(Qt::lightGray);
        }
    }
}

void MainWindow::setDarkTheme(bool enabled) {
    qDebug() << "qApp->style() = " << qApp->style();//windowsvista

    if (enabled) {
        // 1. 切换样式
        qApp->setStyle("Fusion");

        // 2. 设置全局暗色调色板
        QPalette darkPalette;
        darkPalette = qApp->palette();

        // 基础颜色
        darkPalette.setColor(QPalette::Window, QColor("#2b2d30"));       // 窗口背景
        darkPalette.setColor(QPalette::WindowText, Qt::white);           // 文字颜色
        darkPalette.setColor(QPalette::Base, QColor(35, 35, 35));        // 输入框背景
        darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53)); // 列表交替行
        darkPalette.setColor(QPalette::ToolTipBase, Qt::white);          // 提示框背景
        darkPalette.setColor(QPalette::ToolTipText, Qt::black);          // 提示框文字
        darkPalette.setColor(QPalette::Text, Qt::white);                 // 文本颜色
        darkPalette.setColor(QPalette::Button, QColor("#2b2d30"));      // 按钮背景
        darkPalette.setColor(QPalette::ButtonText, Qt::white);           // 按钮文字
        darkPalette.setColor(QPalette::BrightText, Qt::red);             // 高亮文字
        darkPalette.setColor(QPalette::Highlight, QColor("#2e436e")); // 选中项高亮
        darkPalette.setColor(QPalette::HighlightedText, Qt::white);      // 选中项文字

        // 禁用状态颜色
        darkPalette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127));
        darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127));

        // 应用色板
        qApp->setPalette(darkPalette);

        qApp->setStyleSheet(R"(
            /* 鼠标悬停 */
            QPushButton:hover {
                border: 1px solid #45484d;
            }
            /* 按下状态 */
            QPushButton:pressed {
                border: 2px solid #2e436e;
            }
            /* 禁用状态 */
            QPushButton:disabled {
                border: 1px solid #333538;
            }
        )");

    } else {
        // 恢复默认主题
        qApp->setStyle("windowsvista");  // 或系统默认样式
        qApp->setPalette(qApp->style()->standardPalette());
        qApp->setStyleSheet("");    // 清除样式表
    }
}

void MainWindow::updateTextFont(QFont font)
{
    m_frame->setAllFonts(font);
    m_textArea->setFont(font);
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    settings->setValue("Notes/isDarkTheme", settings->value("Notes/isDarkTheme", false).toBool());
    settings->setValue("Notes/textAreaType", textAreaType);

    bool isNoState = windowState() == Qt::WindowNoState;
    if (isNoState) {
        int window_x = this->frameGeometry().x();
        int window_y = this->frameGeometry().y();
        int window_wide = this->geometry().width();
        int window_high = this->geometry().height();

        settings->setValue("Notes/window_x", window_x);
        settings->setValue("Notes/window_y", window_y);
        settings->setValue("Notes/window_wide", window_wide);
        settings->setValue("Notes/window_high", window_high);
    }

    int list1_row = list1->currentRow();
    int list2_row = list2->currentRow();
    QString list1Value = list1_row == -1 ? "" : list1->currentItem()->text();
    QString list2Value = list2_row == -1 ? "" : list2->currentItem()->text();

    settings->setValue("Notes/list1Value", list1Value);
    settings->setValue("Notes/list2Value", list2Value);

    if (textAreaType == 0) {
        //#include <QScrollBar> 需要包含头文件才能用 sliderPosition
        settings->setValue("TextEdit/verticalScroll", m_textArea->verticalScrollBar()->sliderPosition());
        //得到光标位置
        settings->setValue("TextEdit/position", m_textArea->textCursor().position());
    }
    else if (textAreaType == 1) {
        settings->setValue("TextEdit/verticalScroll", m_frame->verticalScrollBar()->sliderPosition());
        //得到光标位置
        int line, index;
        m_frame->getCursorPosition(&line, &index);
        settings->setValue("TextEdit/CursorPosition_line", line);
        settings->setValue("TextEdit/CursorPosition_index", index);
    }
}

void MainWindow::moveEvent(QMoveEvent *event)
{
    if (this->windowState() == Qt::WindowNoState) {
        oldPos = event->oldPos();
        //qDebug() << "Window moved. oldPos:" << oldPos;
    }
    QMainWindow::moveEvent(event); // 调用父类的处理方法
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    if (this->windowState() == Qt::WindowNoState) {
        oldSize = event->oldSize();
        //qDebug() << "Window resized. oldSize:" << oldSize;
    }
    QMainWindow::resizeEvent(event); // 调用父类的处理方法
}


void MainWindow::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::WindowStateChange) {
        if (this->windowState() == Qt::WindowMaximized) {
            // 从普通大小切换到最大化
            int old_window_x = oldPos.x();
            int old_window_y = oldPos.y();
            int old_window_wide = oldSize.rwidth();
            int old_window_high = oldSize.rheight();
            //qDebug() << "old_window_x:" << old_window_x;
            //qDebug() << "old_window_y:" << old_window_y;
            //qDebug() << "old_window_wide:" << old_window_wide;
            //qDebug() << "old_window_high:" << old_window_high;

            settings->setValue("Notes/window_x", old_window_x);
            settings->setValue("Notes/window_y", old_window_y);
            settings->setValue("Notes/window_wide", old_window_wide);
            settings->setValue("Notes/window_high", old_window_high);
        }
        settings->setValue("Notes/WindowState", static_cast<int>(this->windowState()));
    }

    QMainWindow::changeEvent(event);
}

void MainWindow::setSelectColor()
{
    QPalette palette = m_textArea->palette();
    if (isDarkTheme) {
        palette.setColor(QPalette::Highlight, QColor("#1D545C"));
        palette.setColor(QPalette::HighlightedText, QColor(Qt::darkGray));
    }
    else {
        palette.setColor(QPalette::Highlight, QColor(Qt::black));
        palette.setColor(QPalette::HighlightedText, QColor(Qt::white));
    }
    m_textArea->setPalette(palette);
}

void MainWindow::on_list1_itemSelectionChanged()
{
    showList2();
}


void MainWindow::on_list2_itemSelectionChanged()
{
    showFileText();
}

void MainWindow::on_list1_itemChanged(QListWidgetItem *item)
{
    //修改目录名
    QString value = item->text();
    QString oldValue = list1Value;
    if (oldValue == value) {
        return;
    }

    QString newFilepath = QDir(rootPath).filePath(value);
    QDir dir(newFilepath);
    if (dir.exists()) {
        // 目录存在
        QMessageBox::warning(this, "警告", value + " 目录已存在，请修改目录名");
        item->setText(oldValue); // 恢复原来的值
        return;
    }

    bool ren = QFile::rename(list1Path, newFilepath);
    if (ren) {
        list1Value = value;
        list1Path = newFilepath;
    } else {
        item->setText(oldValue); // 恢复原来的值
        qDebug() << oldValue << "文件名修改失败!";
    }
}

void MainWindow::on_list2_itemChanged(QListWidgetItem *item)
{
    //修改文件名
    QString value = item->text();
    QString oldValue = list2Value;
    if (oldValue == value) {
        return;
    }
    QString newFilepath = QDir(list1Path).filePath(value);
    QFile file(newFilepath);
    if (file.exists()) {
        // 文件存在
        QMessageBox::warning(this, "警告", value + " 文件已存在，请修改文件名");
        item->setText(oldValue); // 恢复原来的值
        return;
    }
    bool ren = QFile::rename(list2Path, newFilepath);
    if (ren) {
        list2Value = value;
        list2Path = newFilepath;
        QFileInfo fileInfo(newFilepath);
        QString fileName = fileInfo.fileName();
        QString suffix = fileInfo.suffix();
        qDebug() << newFilepath << "文件名修改成功!\nnewFilepath=" << newFilepath << "," << "suffix=" << suffix;
        m_frame->updateLexer(fileName, suffix, isDarkTheme);
    } else {
        qDebug() << oldValue << "文件名修改失败!";
        item->setText(oldValue); // 恢复原来的值
    }
}

void MainWindow::on_list1_customContextMenuRequested(const QPoint &pos)
{
    qDebug() << "目录右键_" << list1->currentItem()->text();
    //目录右键
    showList2();
    if (list1->itemAt(pos) != NULL) {
        popMenu_L->exec(QCursor::pos());
    }
}

void MainWindow::on_list2_customContextMenuRequested(const QPoint &pos)
{
    //文件右键
    showFileText();
    if (list2->itemAt(pos) != NULL) {
        popMenu_R->exec(QCursor::pos());
    }
}

void MainWindow::on_makeDir_clicked()
{
    makeDir();
}

void MainWindow::on_makeFile_clicked()
{
    makeFile();
}

void MainWindow::on_textArea_textChanged()
{
    if (list2->currentRow() != -1 && isSave && otherFile.isEmpty()) {
        MyUtils::setItemTextColor(list2->currentItem(), "red");
        isSave = false;
    }
    m_frame->updateLineNumberWidth();//设置页边宽度
}

void MainWindow::on_list2_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    //切换选择item时候调用
    if (current != nullptr) {
    }
    if (previous != nullptr && (QColor().black() != previous->foreground().color().value())) {
        MyUtils::setItemTextColor(previous, defaultTextColorName);
    }
}

void MainWindow::newDocument()
{
    qDebug() << "newDocument";
}

void MainWindow::open()
{
    //QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
    QString fileName = QFileDialog::getOpenFileName(this, "Open the file", QDir::homePath());
    QFile file(fileName);
    otherFile = fileName;
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        //QMessageBox::warning(this, "Warning", "Cannot open file: " + file.errorString());
        return;
    }
    file.close();

    setWindowTitle(fileName);
    QString text = FileUtils::getFileString(fileName);
    setTextArea(text);

    if (list2->currentRow() != -1) {
        isClearList2 = true;
        list2->currentItem()->setSelected(false);
        //        list2->setCurrentItem(nullptr);
        isClearList2 = false;
    }
}

void MainWindow::save()
{
    if (!m_frame->isEnabled()) {
        return;
    }
    QString text = getTextArea();
    if (otherFile.isEmpty()) {
        if (list2->currentRow() != -1) {
            if (isSave) {
                return;
            }
            MyUtils::setItemTextColor(list2->currentItem(), defaultTextColorName);
            QString tmp = QDir(rootPath).filePath(list1->currentItem()->text());
            QString filename = QDir(tmp).filePath(list2->currentItem()->text());
            //qDebug() << "filename=" << filename;
            FileUtils::writeStringToFile(filename, text);
            setWindowTitle(list1Value + "/" + list2Value);
            isSave = true;
        }
        else {
            saveAs(rootPath);
        }
    }
    else {
        FileUtils::writeStringToFile(otherFile, text);
    }
}

void MainWindow::saveAsAct()
{
    if (!m_frame->isEnabled()) {
        return;
    }
    if (list2Path.isEmpty()) {
        saveAs(QDir::homePath() + "/" + list2Value);
    }
    else {
        saveAs(list2Path);
    }
}
void MainWindow::saveAs(QString defaultName)
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save as", defaultName);
    //QString fileName = QFileDialog::getSaveFileName(this, "Save as");
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        //QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    QString text = getTextArea();
    FileUtils::writeStringToFile(fileName, text);
}

void MainWindow::copy()
{
#if QT_CONFIG(clipboard)
    if(textAreaType==0)
    {
        m_textArea->copy();
    }
    else if(textAreaType==1)
    {
        m_frame->copy();
    }
#endif
}
void MainWindow::cut()
{
#if QT_CONFIG(clipboard)
    if(textAreaType==0)
    {
        m_textArea->cut();
    }
    else if(textAreaType==1)
    {
        m_frame->cut();
    }
#endif
}
void MainWindow::paste()
{
#if QT_CONFIG(clipboard)
    if(textAreaType==0)
    {
        m_textArea->paste();
    }
    else if(textAreaType==1)
    {
        m_frame->paste();
    }
#endif
}
void MainWindow::undo()
{
    if(textAreaType==0)
    {
        m_textArea->undo();
    }
    else if(textAreaType==1)
    {
        m_frame->undo();
    }
}
void MainWindow::redo()
{
    if(textAreaType==0)
    {
        m_textArea->redo();
    }
    else if(textAreaType==1)
    {
        m_frame->redo();
    }
}

void MainWindow::selectFont()
{
    bool fontSelected;
    QFont font = QFontDialog::getFont(&fontSelected, m_frame->getCurrentFont(), this, "选择字体");
    if (fontSelected) {
        this->updateTextFont(font);
        settingManage->setTextFont(font);
    }
}


void MainWindow::exit()
{
    this->close();
    //    QCoreApplication::quit();
}

void MainWindow::on_actionJumpToTopButton_triggered()
{
    if (textAreaType == 0) {
        m_textArea->verticalScrollBar()->setValue(m_textArea->verticalScrollBar()->minimum());
    }
    else if (textAreaType == 1) {
        m_frame->SendScintilla(m_frame->SCI_GOTOPOS, 0);
    }
}

void MainWindow::on_actionJumpToBottomButton_triggered()
{
    if (textAreaType == 0) {
        m_textArea->verticalScrollBar()->setValue(m_textArea->verticalScrollBar()->maximum());
    }
    else if (textAreaType == 1) {
        m_frame->SendScintilla(m_frame->SCI_GOTOPOS, m_frame->length());
    }
}

void MainWindow::applySetting()
{
    qDebug() << "应用设置applySetting";
}

void MainWindow::showDir()
{
    showExplorer(list1Path);
}
void MainWindow::showFile()
{
    showExplorer(list2Path);
}

void MainWindow::deleteDir()
{
    QString path = list1Path;
    int ret = QMessageBox::question(this,"删除","确定删除：" + list1Value + " ?",
                                    QMessageBox::Yes | QMessageBox::Cancel);
    if (ret != QMessageBox::Yes) {
        return;
    }
    QDir dir(path);
    bool s = dir.removeRecursively();
    if (s) {
        //qDebug() << path << ",删除成功√";
        QListWidgetItem *item = list1->currentItem();
        list1->removeItemWidget(item);
        delete item;
        showList2();
    }
    else {
        qDebug() << path << ",删除失败!";
    }
}

void MainWindow::deleteFile()
{
    QString filename = list2Path;
    int ret = QMessageBox::question(this,"删除","确定删除：" + list2Value + " ?",
                                    QMessageBox::Yes | QMessageBox::Cancel);
    if (ret != QMessageBox::Yes) {
        return;
    }
    bool s = QFile::remove(filename);
    if (s) {
        //qDebug() << filename << ",删除成功√";
        QListWidgetItem *item = list2->currentItem();
        list2->removeItemWidget(item);
        delete item;
        showFileText();
    }
    else {
        qDebug() << filename << ",删除失败!";
    }
}

//转换大写
void MainWindow::upper() {
    if (textAreaType == 0) {
        // 获取选中的文本
        QString selectedText = m_textArea->textCursor().selectedText();
        // 转换为大写
        QString upperCaseText = selectedText.toUpper();
        // 将转换后的文本替换选中的文本
        m_textArea->textCursor().insertText(upperCaseText);
    } else if (textAreaType == 1) {
    }
}

//转换小写
void MainWindow::lower() {
    if (textAreaType == 0) {
        // 获取选中的文本
        QString selectedText = m_textArea->textCursor().selectedText();
        // 转换为小写
        QString lowerCaseText = selectedText.toLower();
        // 将转换后的文本替换选中的文本
        m_textArea->textCursor().insertText(lowerCaseText);
    } else if (textAreaType == 1) {
    }
}

//向上移动一行
void MainWindow::moveSelectedLinesUp() {
    qDebug() << "lineUp";
    if (textAreaType == 0) {
        // 获取当前选中文本的起始和结束位置
        QTextCursor cursor = m_textArea->textCursor();
        int start = cursor.selectionStart();
        int end = cursor.selectionEnd();
        if (start == end) return;

        // 获取当前选中的文本
        QString selectedText = m_textArea->toPlainText().mid(start, end - start);

        // 移动文本内容一行（向上）
        cursor.setPosition(start);
        cursor.movePosition(QTextCursor::StartOfLine);
        cursor.removeSelectedText(); // 删除当前选中文本的起始行
        cursor.movePosition(QTextCursor::PreviousBlock); // 移动到前一行
        cursor.insertText(selectedText); // 在前一行插入选中文本

    } else if (textAreaType == 1) {
        // 向上移动当前选中的行
        m_frame->SendScintilla(QsciScintilla::SCI_MOVESELECTEDLINESUP);
    }
}

//向下移动一行
void MainWindow::moveSelectedLinesDown() {
    qDebug() << "lineDown";
    if (textAreaType == 0) {
        // 获取当前选中文本的起始和结束位置
        QTextCursor cursor = m_textArea->textCursor();
        int start = cursor.selectionStart();
        int end = cursor.selectionEnd();
        if (start == end) return;

        // 获取当前选中的文本
        QString selectedText = m_textArea->toPlainText().mid(start, end - start);

        // 移动文本内容一行（向下）
        cursor.setPosition(start);
        cursor.movePosition(QTextCursor::EndOfLine);
        cursor.removeSelectedText(); // 删除当前选中文本的结束行
        cursor.movePosition(QTextCursor::NextBlock); // 移动到后一行
        cursor.insertText(selectedText); // 在后一行插入选中文本
    } else if (textAreaType == 1) {
        // 向下移动当前选中的行
        m_frame->SendScintilla(QsciScintilla::SCI_MOVESELECTEDLINESDOWN);
    }
}

void MainWindow::showAboutDialog()
{
    AboutDialog aboutDialog(this);
    aboutDialog.exec();  // 显示模态对话框
}

void MainWindow::showExplorer(QString path)
{
    path = QDir::toNativeSeparators(path);

    QProcess proce;
    QString cmd = QString("explorer /select, \"%1\"").arg(path);
    proce.startDetached(cmd);
}

//########################################################
void MainWindow::makeDir()
{
    FileUtils::mkdirs(rootPath);
    qDebug() << "rootPath=" << rootPath;
    QString dir_str = MyUtils::getNewDirName(rootPath);
    qDebug() << "dir_str=" << dir_str;
    QString fileName = rootPath + "/" + dir_str;
    // 检查目录是否存在，若不存在则新建
    bool rel = FileUtils::mkdirs(fileName);

    qDebug() << "fileName=" << fileName;
    qDebug() << "rel=" << rel;

    if (rel) {
        QListWidgetItem *aitem = new QListWidgetItem(dir_str);
        aitem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
        list1->addItem(aitem);
    } else {
        qDebug() << "目录创建失败X!" << fileName;
    }
}

void MainWindow::makeFile()
{
    if (list1->currentRow() == -1) {
        qDebug() << "不创建！" ;
        return;
    }
    QDir dir(list1Path);
    if (!dir.exists()) {
        //如果存在上级目录就创建文件
        qDebug() << list1Path << ",目录不存在!";
        return;
    }
    QString newName = MyUtils::getNewFileName(list1Path);
    QString filePath = QDir(list1Path).filePath(newName);

    bool rel = FileUtils::createNewFile(filePath);
    if (rel) {
        QListWidgetItem *aitem = new QListWidgetItem(newName);
        aitem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
        list2->addItem(aitem);
    }
}

void MainWindow::showList2() {
    //解决从空白处按住鼠标拖到item上选中数据不一致或异常等问题
    if (list1->currentItem() == nullptr) {
        QListWidgetItem *selItem = list1->selectedItems().takeAt(0);
        qDebug() << "selItem->text()" << selItem->text();
        list1->setCurrentItem(selItem);
    } else {
        QListWidgetItem *selItem = list1->selectedItems().takeAt(0);
        qDebug() << "selItem->text()" << selItem->text() << "curItem" << list1->currentItem()->text();
        if (!list1->currentItem()->isSelected()) {
            list1->setCurrentItem(selItem);
        }
    }

    QListWidgetItem *curItem = list1->currentItem();
    bool isNull = list1->currentItem() == nullptr;
    qDebug() << "isNull" << isNull;
    if (!isNull) {
        QString value = curItem->text();
        if(list1Value == value) return;
        list1Value = value;
        list1Path = QDir(rootPath).filePath(list1Value);
        qDebug() << "list1Path" << list1Path;
        qDebug() << "list1Value" << list1Value;
    }

    isClearList2 = true;
    list2->clear();
    list2Value.clear();
    list2Path.clear();
    otherFile.clear();
    isClearList2 = false;

    cleanTextArea();

    if (!isNull) {
        setWindowTitle(list1Value);
        QStringList list = FileUtils::getFileList(list1Path);
        WidgetUtils::putListItem(list2, list);
    }
}

void MainWindow::showFileText() {
    if (isClearList2) return;

    qDebug() << "isNull" << (list2->currentItem() == nullptr) << "rowFile" << list2->currentRow();

    //解决从空白处按住鼠标拖到item上选中数据不一致或异常等问题
    if (list2->currentItem() == nullptr) {
        QListWidgetItem *selItem = list2->selectedItems().takeAt(0);
        qDebug() << "selItem->text()" << selItem->text();
        list2->setCurrentItem(selItem);
    } else {
        QListWidgetItem *selItem = list2->selectedItems().takeAt(0);
        qDebug() << "selItem->text()" << selItem->text() << "curItem" << list2->currentItem()->text();
        if (!list2->currentItem()->isSelected()) {
            list2->setCurrentItem(selItem);
        }
    }

    if (!otherFile.isEmpty()) otherFile.clear();

    if (list2->currentRow() == -1) {
        cleanTextArea();
        return;
    } else {
        QString value = list2->currentItem()->text();
        if (list2Value == value) return;
        QString absName = QDir(list1Path).filePath(value);
        list2Value = value;
        list2Path = absName;
        setWindowTitle(list1Value + "/" + value);
        QFileInfo fileInfo(absName);
        if (fileInfo.isFile()) {
            QString fileName = fileInfo.fileName();
            QString suffix = fileInfo.suffix();
            m_frame->updateLexer(fileName, suffix, isDarkTheme);
            QString text = FileUtils::getFileString(absName);
            setTextArea(text);
        } else {
            cleanTextArea();
        }
    }
}

//
// 清空TextArea
//
void MainWindow::cleanTextArea()
{
    isSave = false;
    isClearTextArea = true;

    if(textAreaType==0)
    {
        m_textArea->setEnabled(false);
        m_textArea->clear();
    }else if(textAreaType==1){
        m_frame->setEnabled(false);
        m_frame->clear();
    }

    isSave = true;
    isClearTextArea = false;
}

//
// 添加TextArea文本
//
void MainWindow::setTextArea(QString text)
{
    isSave = false;
    isClearTextArea = true;

    if(textAreaType==0)
    {
        m_textArea->clear();
        m_textArea->setEnabled(true);
        m_textArea->setPlainText(text);
    }else if(textAreaType==1){
        m_frame->clear();
        m_frame->setEnabled(true);
        m_frame->setText(text);
        m_frame->setScrollWidth(5);
    }
    isSave = true;
    isClearTextArea = false;
}

//
// 获取TextArea文本
//
QString MainWindow::getTextArea()
{
    QString text;
    if(textAreaType==0)
    {
        text = m_textArea->toPlainText();
    }
    else if(textAreaType==1)
    {
        text = m_frame->text();
    }
    return text;
}
